//
//  PKReadMainViewController.m
//  PianKe
//
//  Created by ybq on 15/12/21.
//  Copyright © 2015年 B7_Young. All rights reserved.
//

#import "PKReadMainViewController.h"
#import "PKReadHeaderCollectionReusableView.h"
#import "PKReadModel.h"
#import "PKReadCollectionViewCell.h"
#import "PKReadDetailViewController.h"
#import "PKReadInfoViewController.h"

@interface PKReadMainViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *listDatasource;
@property (nonatomic, strong) NSMutableArray *carouselDatasource;
@property (nonatomic, strong) PKReadHeaderCollectionReusableView *headerView;

@end

@implementation PKReadMainViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self changeNavViewTitle];
    [self requestData];
    [self creatUI];
}

// 自定义请求数据的方法
- (void)requestData {
    
    _listDatasource = [NSMutableArray array];
    _carouselDatasource = [NSMutableArray array];
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"BsdsQiiw9K9DCMVzGMTikDJxQ8auML6E82dsXj1lcWP23tBPTxRY4Pw";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"07EBFC18-9BF8-47D1-9FEA-79BBF44D4C9E";
    parDic[@"version"] = @"3.0.6";
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/read/columns" parDic:parDic Method:POST finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *listArray = dataDic[@"data"][@"list"];
        NSArray *carouselArray = dataDic[@"data"][@"carousel"];
        [_listDatasource removeAllObjects];
        [_carouselDatasource removeAllObjects];
        for (NSDictionary *dic in listArray) {
            PKReadModel *model = [[PKReadModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_listDatasource addObject:model];
        }
        
        for (NSDictionary *dic in carouselArray) {
            PKReadModel *model = [[PKReadModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_carouselDatasource addObject:model];
        }
        self.getData();
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
    } error:^(NSError *error) {
        
    }];
}

- (void)creatUI {
    // 创建一个网状结构布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置网状结构的具体属性
    // 最小行间距
    layout.minimumLineSpacing = 3;
//    // 最小列间距
    layout.minimumInteritemSpacing = 3;
    // item的大小
//    layout.itemSize = CGSizeMake(120, 120);
    // 表头size
    layout.headerReferenceSize = CGSizeMake(10, 200);
    // 表尾size
    layout.footerReferenceSize = CGSizeMake(100, 300);
    // 滚动方向 默认是竖着滑动
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 内边距
    layout.sectionInset = UIEdgeInsetsMake(5, 3, 4, 3);
    //    // 设置item强制size
    layout.estimatedItemSize = CGSizeMake(120, 120);
    // 表头表尾大小
    layout.headerReferenceSize = CGSizeMake(kWidth, 175);
    layout.footerReferenceSize = CGSizeMake(kWidth, 125);
    // 创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64) collectionViewLayout:layout];
    // 设置代理 数据源
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    // 设置背景颜色(默认黑色)
    self.collectionView.backgroundColor = [UIColor whiteColor];
    // 显示视图
    [self.view addSubview:self.collectionView];
    
    // MJRefresh
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestData];
    }];
    
    // 注册要使用的cell
    [self.collectionView registerClass:[PKReadCollectionViewCell class] forCellWithReuseIdentifier:@"PKReadCollectionViewCell"];
    // 注册表头表尾
    [self.collectionView registerClass:[PKReadHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PKReadHeaderCollectionReusableView"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myFooterView"];
}

#pragma mark -- 代理方法
// 返回每个分区 有多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _listDatasource.count;
}
// 返回每个索引下 UICollectionViewCell的样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 与UItableView 相同
    // 重用池中有可以用的就拿去用(返回给你) 如果没有就创建一个
    // 必须注册一下要使用的标识符的cell 才能使用
    // 系统才知道 要从重用池中 取哪个类型的cell
    
    PKReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PKReadCollectionViewCell" forIndexPath:indexPath];
    PKReadModel *model = _listDatasource[indexPath.row];
    [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:nil];
    NSString *str = model.name;
    CGRect titleRect = [str boundingRectWithSize:CGSizeMake( 300, 100) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15] } context:nil];
    CGSize titleSize = titleRect.size;
//    NSLog(@"titleSize.width=%f, titleSize.height=%f", titleSize.width, titleSize.height);

    //根据计算结果重新设置UILabel的尺寸
    
    [cell.nameLabel setFrame:CGRectMake(2, 98, titleSize.width, 20)];
    
    cell.nameLabel.text = str;
    
    [cell.ennameLabel setFrame:CGRectMake(cell.nameLabel.frame.origin.x + cell.nameLabel.frame.size.width + 2, 102, 60, 15)];
    cell.ennameLabel.text = model.enname;
    return cell;
}

// 设置表头和表尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    // 判断返回表头类型还是表尾类型
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        // 表头
        
        // 相当于去重用池中去找 判断一下 有就用 没有就建
        // UICollectionElementKindSectionHeader (表头的类型)
        // 可重用的View 分为两种 一种表头 一种表尾
        _headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PKReadHeaderCollectionReusableView" forIndexPath:indexPath];
        _headerView.userInteractionEnabled = YES;
        
        __weak PKReadMainViewController *myself = self;
        myself.getData= ^() {
            _headerView.count = (int)_carouselDatasource.count;
            _headerView.scrollView.contentSize = CGSizeMake(kWidth * (_headerView.count + 1), 175);
            
            _headerView.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(kWidth - 70, 150, 50, 20)];
            _headerView.pageControl.numberOfPages = _headerView.count;
            [_headerView addSubview:_headerView.pageControl];
            
            NSTimer *timer =  [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction:) userInfo:@"图片轮播" repeats:YES];
            _headerView.num = 0;
            [timer fire];
            // 创建轮播图的imageView
           
            for (int i = 0; i < (_headerView.count + 1); i++) {
                UIImageView *carouselImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth * i, 0, kWidth, 175)];
                // 开启交互
                carouselImageView.userInteractionEnabled = YES;
                [_headerView.scrollView addSubview:carouselImageView];
                carouselImageView.tag = 1000 + i;
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(carouseAction:)];
                [carouselImageView addGestureRecognizer:tap];
                
                if (i < _headerView.count) {
                    PKReadModel *carouseModel = _carouselDatasource[i];
                    [carouselImageView sd_setImageWithURL:[NSURL URLWithString:carouseModel.img]];
                } else {
                    [carouselImageView sd_setImageWithURL:[NSURL URLWithString:((PKReadModel *)_carouselDatasource[0]).img]];
                }
            }
        };
        return _headerView;
        
    }  else {
        // 表尾
//        
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myFooterView" forIndexPath:indexPath];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 0, kWidth - 10, 120)];
        imageView.image = [UIImage imageNamed:@"footerView.jpg"];
        [footerView addSubview:imageView];
        return footerView;
    }
}



// NSTimer实现
- (void)timerAction:(NSTimer *)timer {
    _headerView.pageControl.currentPage = _headerView.num;
    [_headerView.scrollView setContentOffset:CGPointMake(kWidth * _headerView.num, 0) animated:NO];
    _headerView.num++;
    if (_headerView.num == _headerView.count) {
        _headerView.num = 0;
    }
    
}

// 实现代理方法
// 连接UIPageControl
// 图片停止减速时触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // 通过偏移量的x坐标 来关联currentPage
    // 取出偏移量
    CGFloat x = scrollView.contentOffset.x;
    NSInteger num = x / kWidth;
    if (num == _headerView.count) {
        num = 0;
    }
    _headerView.pageControl.currentPage = num;
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.x > kWidth * _headerView.count) {
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    
    if (scrollView.contentOffset.x < 0) {
        [scrollView setContentOffset:CGPointMake(kWidth * _headerView.count, 0) animated:NO];
    }
    
}


- (void)carouseAction:(UITapGestureRecognizer *)tap {
    UIImageView *carouselImageView = (UIImageView *)tap.view;
    NSInteger index = carouselImageView.tag - 1000;
    if (carouselImageView.tag == 1003) {
        index = 0;
    }
    PKReadModel *model = _carouselDatasource[index];
    NSString *contentid = [model.url substringFromIndex:17];
    PKReadInfoViewController *readInfoVC = [[PKReadInfoViewController alloc] init];
    readInfoVC.contentid = contentid;
    [self.navigationController pushViewController:readInfoVC animated:YES];
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PKReadModel *model = _listDatasource[indexPath.row];
    PKReadDetailViewController *readDetailVC = [[PKReadDetailViewController alloc] init];
    readDetailVC.typeId = model.type;
    readDetailVC.typeName = model.name;
    [self.navigationController pushViewController:readDetailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
